/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JDialogMoteConfig.java
 *
 * Created on Aug 13, 2009, 1:39:09 PM
 */

package com.wisc.csvParser.plugins.CrossbowMoteParser;

import com.wisc.csvParser.ValueObjectJPanel;
import com.wisc.csvParser.plugins.CrossbowMoteParser.DataSourceDNRMotes.Mote;
import com.wisc.csvParser.plugins.CrossbowMoteParser.DataSourceDNRMotes.Mote.ColumnObject;
import java.awt.CardLayout;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;


/**
 *
 * @author lawinslow
 */
public class JDialogMoteConfig extends javax.swing.JDialog {

    Mote mote;

    Vector<ColumnObject> columns = new Vector<ColumnObject>();
    Hashtable<ColumnObject,ValueObjectJPanel> settingsPanels =
            new Hashtable<ColumnObject,ValueObjectJPanel>();


    ValueObjectJPanel panel;
    /** Creates new form JDialogMoteConfig
     * @param parent
     * @param modal
     * @param mote
     */
    public JDialogMoteConfig(java.awt.Frame parent, boolean modal,Mote mote) {
        super(parent, modal);
        initComponents();

        this.mote = mote;

        for(Object obj:mote.getColumns().values()){
            ColumnObject col = ((ColumnObject)obj).clone();
            columns.add(col);
            settingsPanels.put(col, new ValueObjectJPanel(col.templateValue));
        }

        moteNameTF.setText(mote.getMoteName());
        tableNameTF.setText(mote.getTable());
        moteIDTF.setText(Integer.toString(mote.getNodeID()));

        updateDisplay();

        
        DocumentListener l = new DocumentListener(){
            @Override
            public void changedUpdate(DocumentEvent e) {
                textFieldChanged(e);
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                textFieldChanged(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                textFieldChanged(e);
            }

        };

        moteNameTF.getDocument().addDocumentListener(l);
        tableNameTF.getDocument().addDocumentListener(l);
        moteIDTF.getDocument().addDocumentListener(l);
        equationTF.getDocument().addDocumentListener(l);
        columnNameTF.getDocument().addDocumentListener(l);

       
    }

    private void updateDisplay(){

        int selectedIndex = columnsList.getSelectedIndex();
        columnsList.removeAll();
        columnsList.setListData(columns);
        if(columns.size()>selectedIndex){
            columnsList.setSelectedIndex(selectedIndex);
        }
    }

    private void textFieldChanged(DocumentEvent e){

        if(e.getDocument().equals(moteIDTF.getDocument())){
            if(!moteIDTF.getText().equalsIgnoreCase("")){
                mote.setNodeID(Integer.parseInt(moteIDTF.getText()));
            }
        }else if(e.getDocument().equals(equationTF.getDocument())){
            if(columnsList.getSelectedValue()!=null){
                columns.get(columnsList.getSelectedIndex()).equation
                        .parseExpression(equationTF.getText());
                 columns.get(columnsList.getSelectedIndex()).equationAsString =
                         equationTF.getText();
            }
        }else if(e.getDocument().equals(columnNameTF.getDocument())){
            if(columnsList.getSelectedValue()!=null){
                 columns.get(columnsList.getSelectedIndex()).columnName =
                         columnNameTF.getText();
                 //updateDisplay();
                 
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        valueSettingsJPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        columnsList = new javax.swing.JList();
        addButton = new javax.swing.JButton();
        removeButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        tableNameTF = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        moteNameTF = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        moteIDTF = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        equationTF = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        columnNameTF = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        valueSettingsJPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        valueSettingsJPanel.setLayout(new java.awt.CardLayout());

        columnsList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                columnsListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(columnsList);

        addButton.setText("Add");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        removeButton.setText("Remove");
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Mote Specific Info"));

        jLabel2.setText("Table Name:");

        jLabel3.setText("Mote Name:");

        jLabel1.setText("Mote ID:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(moteIDTF, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(moteNameTF, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE)
                    .addComponent(tableNameTF, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(moteNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tableNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(moteIDTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(4, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Column Info"));

        jLabel4.setText("Equation: (x is raw database value)");

        jLabel5.setText("Column Name:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(equationTF, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(columnNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel5)
                .addContainerGap())
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel4)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(equationTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addGap(1, 1, 1)
                .addComponent(columnNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        saveButton.setText("Save");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(addButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(removeButton))
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(valueSettingsJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addButton)
                    .addComponent(removeButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap(16, Short.MAX_VALUE))
            .addComponent(valueSettingsJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 441, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void columnsListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_columnsListValueChanged

        if (!(evt instanceof javax.swing.event.ListSelectionEvent)){
            return;
        }



        if(columnsList.getSelectedValue()==null){
            return;
        }
        ColumnObject col = columns.get(columnsList.getSelectedIndex());
        showPanel(settingsPanels.get(col));

        
        equationTF.setText(col.equationAsString);
        columnNameTF.setText(col.columnName);
    }//GEN-LAST:event_columnsListValueChanged

    private void showPanel(ValueObjectJPanel p){
        if(p==null)
            return;
        if(panel!=null)//remove last displayed panel
            valueSettingsJPanel.remove(panel);
        
        panel = p;
        valueSettingsJPanel.add(panel,"settings");
        valueSettingsJPanel.validate();

        ((CardLayout)valueSettingsJPanel.getLayout())
                .show(valueSettingsJPanel, "settings");
    }

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed

        ColumnObject col = mote.getNewColumn();
        settingsPanels.put(col, new ValueObjectJPanel(col.templateValue));
        columns.add(col);

        updateDisplay();
    }//GEN-LAST:event_addButtonActionPerformed

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
        if(columnsList.getSelectedIndex() >=0){
            columns.remove(columnsList.getSelectedIndex());
            updateDisplay();
        }
    }//GEN-LAST:event_removeButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        
        for(ColumnObject col:settingsPanels.keySet()){
            ValueObjectJPanel p = settingsPanels.get(col);
            
            if(col.equation.hasError()){
                columnsList.setSelectedValue(col,false);
                javax.swing.JOptionPane.showMessageDialog(null,
                        "Error in equation entered. \nPlease check " +
                        "equation.");
                return;
            }
            if(!p.checkAndSave()){
                columnsList.setSelectedValue(col,false);
                javax.swing.JOptionPane.showMessageDialog(null,
                        "Unable to save column metadata. \nPlease check " +
                        "metadata displayed.");
                return;
            }

        }

        mote.getColumns().clear();
        for(ColumnObject c:columns){
            mote.addColumn(c);
        }

        //TODO: Add checking of these input fields
        mote.setMoteName(moteNameTF.getText());
        mote.setNodeID(Integer.parseInt(moteIDTF.getText()));
        mote.setTable(tableNameTF.getText());

        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextField columnNameTF;
    private javax.swing.JList columnsList;
    private javax.swing.JTextField equationTF;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField moteIDTF;
    private javax.swing.JTextField moteNameTF;
    private javax.swing.JButton removeButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextField tableNameTF;
    private javax.swing.JPanel valueSettingsJPanel;
    // End of variables declaration//GEN-END:variables

}
